<template>
  <div class="success-page">
    <div class="container">
      <!-- 返回按钮 -->
      <button class="back-btn" @click="convertNew">
        ← 返回
      </button>

      <!-- 标题区域 -->
      <div class="page-header">
        <h1 class="page-title">SVG预览</h1>
      </div>

      <!-- 主内容卡片 -->
      <div class="content-card">
        <!-- SVG预览区域 -->
        <div class="svg-preview-section">
          <!-- 加载状态 -->
          <div v-if="imageLoading" class="image-loading">
            <div class="loading-spinner"></div>
            <p>加载SVG中...</p>
            <p class="loading-hint">{{ loadingHint }}</p>
          </div>
          <!-- SVG图片 -->
          <img 
            v-show="!imageLoading"
            :src="svgDataWithTimestamp" 
            alt="SVG预览" 
            class="svg-image" 
            @load="handleImageLoad"
            @error="handleImageError" 
          />
        </div>

        <!-- 下载按钮 -->
        <button class="download-btn" @click="downloadSvg" :disabled="downloading">
          {{ downloading ? '下载中...' : '下载 SVG' }}
        </button>

        <!-- 文件信息列表 -->
        <div class="info-list">
          <div class="info-row">
            <span class="info-label">尺寸大小:</span>
            <span class="info-value">{{ svgData.svgWidth }} × {{ svgData.svgHeight }} px</span>
          </div>
          <div class="info-row">
            <span class="info-label">文件大小:</span>
            <span class="info-value">{{ formatFileSize(svgData.svgFileSize) }}</span>
          </div>
        </div>
      </div>

      <!-- 成功提示 -->
      <div class="success-message">
        <span class="success-icon">✓</span>
        <div class="success-text">
          <strong>SVG 生成成功！</strong>
          <p>您的SVG已经准备就绪，可以预览、下载或分享。页面刷新后仍可正常访问。</p>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { toastSuccess, toastError } from '@/utils/toast'

const router = useRouter()
const svgData = ref({
  svgUrl: '',
  svgFilename: '',
  svgFileSize: 0,
  svgWidth: 0,
  svgHeight: 0
})

const imageLoading = ref(true)
const downloading = ref(false)
const loadingHint = computed(() => {
  const sizeMB = (svgData.value.svgFileSize / (1024 * 1024)).toFixed(2)
  if (sizeMB > 10) {
    return `文件较大（${sizeMB}MB），请耐心等待...`
  } else if (sizeMB > 5) {
    return `正在加载 ${sizeMB}MB 的SVG文件...`
  }
  return ''
})

// 添加时间戳参数防止浏览器缓存
const svgDataWithTimestamp = computed(() => {
  if (!svgData.value.svgUrl) return ''
  const separator = svgData.value.svgUrl.includes('?') ? '&' : '?'
  return `${svgData.value.svgUrl}${separator}t=${Date.now()}`
})

// 图片加载完成
const handleImageLoad = () => {
  imageLoading.value = false
  console.log('SVG加载成功')
}

// 图片加载错误处理
const handleImageError = (event) => {
  imageLoading.value = false
  console.error('SVG加载失败:', svgData.value.svgUrl)
  console.error('完整URL:', event.target.src)
  
  // 🔑 优化：检查是否是浏览器回退导致的数据丢失
  const resultData = sessionStorage.getItem('conversionResult')
  if (!resultData) {
    // 如果是浏览器回退导致数据丢失，自动跳转回文件转SVG页面
    console.warn('检测到浏览器回退，数据已丢失，自动返回文件转SVG页面')
    router.push('/file-to-svg')
    return
  }
  
  toastError('SVG加载失败，请刷新页面重试')
}

onMounted(() => {
  // 从sessionStorage获取转换结果数据
  const resultData = sessionStorage.getItem('conversionResult')
  if (resultData) {
    try {
      const data = JSON.parse(resultData)
      // 🔑 验证数据完整性
      if (!data.svgUrl) {
        console.warn('SVG数据不完整，跳转回文件转SVG页面')
        router.push('/file-to-svg')
        return
      }
      svgData.value = data
      console.log('转换结果数据:', data)
      console.log('SVG URL:', data.svgUrl)
    } catch (error) {
      console.error('解析转换结果数据失败:', error)
      // 🔑 数据解析失败，跳转回文件转SVG页面
      router.push('/file-to-svg')
    }
  } else {
    // 如果没有数据，跳转回文件转SVG页面
    console.warn('未找到转换结果数据，跳转回文件转SVG页面')
    router.push('/file-to-svg')
  }
})

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
  return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}

// 转换新文件
const convertNew = () => {
  // 清除sessionStorage中的数据
  sessionStorage.removeItem('conversionResult')
  // 跳转回文件转SVG页面
  router.push('/file-to-svg')
}

// 直接下载（不跳转页面）
const downloadSvg = async () => {
  if (!svgData.value.svgUrl) {
    toastError('下载地址不存在')
    return
  }
  
  if (downloading.value) {
    return // 防止重复下载
  }
  
  try {
    downloading.value = true
    const downloadUrl = svgData.value.svgUrl
    const filename = svgData.value.svgFilename || 'output.svg'
    
    // 判断是否为外部URL（COS URL）
    const isExternalUrl = downloadUrl.startsWith('http://') || downloadUrl.startsWith('https://')
    
    if (isExternalUrl && !downloadUrl.includes('/api/files/')) {
      // 对于COS URL，直接创建下载链接（避免CORS问题）
      const a = document.createElement('a')
      a.href = downloadUrl
      a.download = filename
      a.target = '_blank'
      document.body.appendChild(a)
      a.click()
      a.remove()
      toastSuccess('开始下载')
    } else {
      // 对于本地URL或代理URL，使用fetch下载
      const url = downloadUrl.includes('?') ? `${downloadUrl}&download=true` : `${downloadUrl}?download=true`
      const res = await fetch(url)
      if (!res.ok) {
        throw new Error('下载失败：' + res.statusText)
      }
      
      const blob = await res.blob()
      const blobUrl = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = blobUrl
      a.download = filename
      document.body.appendChild(a)
      a.click()
      URL.revokeObjectURL(blobUrl)
      a.remove()
      toastSuccess('下载成功')
    }
  } catch (error) {
    console.error('下载失败:', error)
    toastError('下载失败: ' + (error.message || '网络错误，稍后重试'))
  } finally {
    downloading.value = false
  }
}
</script>

<style scoped>
.success-page {
  min-height: 100vh;
  width: 100vw;
  background: #f5f7fa;
  padding: 40px 20px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow-x: hidden;
}

.container {
  max-width: 600px;
  width: 100%;
  margin: 0 auto;
}

/* 返回按钮 */
.back-btn {
  background: white;
  border: 1px solid #e5e7eb;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 0.95rem;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 20px;
  font-weight: 500;
}

.back-btn:hover {
  background: #f9fafb;
  border-color: #d1d5db;
}

/* 页面标题 */
.page-header {
  background: #e0e7ff;
  padding: 16px 24px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.header-icon {
  font-size: 1.5rem;
}


.page-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

/* 主内容卡片 */
.content-card {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* SVG预览区域 */
.svg-preview-section {
  background: #f9fafb;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  margin-bottom: 24px;
}

.svg-image {
  max-width: 100%;
  max-height: 500px;
  width: auto;
  height: auto;
  display: block;
  object-fit: contain;
  border-radius: 8px;
}

/* 加载状态 */
.image-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #e5e7eb;
  border-top-color: #6366f1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.image-loading p {
  color: #6b7280;
  font-size: 0.95rem;
  margin: 0;
}

.loading-hint {
  font-size: 0.85rem !important;
  color: #9ca3af !important;
  font-style: italic;
}

/* 下载按钮 */
.download-btn {
  width: 100%;
  background: #10b981;
  color: white;
  border: none;
  padding: 16px;
  border-radius: 10px;
  font-size: 1.05rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 24px;
}

.download-btn:hover:not(:disabled) {
  background: #059669;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.download-btn:disabled {
  background: #9ca3af;
  cursor: not-allowed;
  opacity: 0.6;
  transform: none;
}

/* 信息列表 */
.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-row {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
  gap: 8px;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 0.95rem;
  color: #6b7280;
  font-weight: 500;
  min-width: 100px;
}

.info-value {
  font-size: 0.95rem;
  color: #111827;
  font-weight: 500;
}

/* 成功提示 */
.success-message {
  background: #d1fae5;
  border: 1px solid #a7f3d0;
  border-radius: 12px;
  padding: 20px 24px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.success-icon {
  width: 28px;
  height: 28px;
  background: #10b981;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  font-weight: bold;
  flex-shrink: 0;
}

.success-text {
  flex: 1;
}

.success-text strong {
  display: block;
  font-size: 1.05rem;
  color: #065f46;
  margin-bottom: 6px;
}

.success-text p {
  font-size: 0.9rem;
  color: #047857;
  margin: 0;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .success-page {
    padding: 16px;
  }

  .content-card {
    padding: 24px;
  }

  .svg-preview-section {
    min-height: 300px;
    padding: 16px;
  }

  .page-title {
    font-size: 1.1rem;
  }

  .download-btn {
    padding: 14px;
    font-size: 1rem;
  }

  .success-message {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .page-header {
    padding: 12px 16px;
  }

  .content-card {
    padding: 20px;
  }

  .info-label {
    font-size: 0.85rem;
    min-width: 80px;
  }

  .info-value {
    font-size: 0.85rem;
  }
}
</style>

